/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "include/core/SkPixelRef.h"

#include "include/private/base/SkAssert.h"
#include "include/private/base/SkDebug.h"
#include "oh/DrawingHash.h"
#include "oh/OHDrawingAPI.h"
#include "src/core/SkBitmapCache.h"
#include "src/core/SkNextID.h"
#include "src/core/SkPixelRefPriv.h"
#include "src/core/SkTraceEvent.h"
#include "src/core/SkTraceEventCommon.h"

#include <atomic>
#include <cstdint>
#include <multimedia/image_framework/image/pixelmap_native.h>
#include <native_drawing/drawing_image.h>
#include <native_drawing/drawing_bitmap.h>
#include <utility>
#include "include/oh/OHEnv.h"

uint32_t SkNextID::ImageID() {
    // We never set the low bit.... see SkPixelRef::genIDIsUnique().
    static std::atomic<uint32_t> nextID{2};

    uint32_t id;
    do {
        id = nextID.fetch_add(2, std::memory_order_relaxed);
    } while (id == 0);
    return id;
}

///////////////////////////////////////////////////////////////////////////////

SkPixelRef::SkPixelRef(int width, int height, void* pixels, size_t rowBytes)
    : fWidth(width)
    , fHeight(height)
    , fPixels(pixels)
    , fRowBytes(rowBytes)
    , fAddedToCache(false)
{
    this->needsNewGenID();
    fMutability = kMutable;
    fbytesPerPixel = fRowBytes / fWidth;
    DrawingHash hasher(DrawingHash::RunningUniqueId());
    hasher.push(fPixels);
    hasher.push(width);
    hasher.push(height);
    hasher.push(rowBytes);
    fHash = hasher.digest();
}

SkPixelRef::SkPixelRef(OH_PixelmapNative* pixelmap)
    : fPixelmap(pixelmap)
    , fAddedToCache(false)
{
    this->needsNewGenID();
    fMutability = kMutable;
    fDrawingPixelmap = OH_Drawing_PixelMapGetFromOhPixelMapNative(fPixelmap);
    
    OH_Pixelmap_ImageInfo *real_info = nullptr;
    OH_PixelmapImageInfo_Create(&real_info);
    OH_PixelmapNative_GetImageInfo(pixelmap, real_info);

    uint32_t real_width = 0, real_height = 0, real_rowBytes = 0;
    int32_t pixel_format, alpha_type;
    OH_PixelmapImageInfo_GetWidth(real_info, &real_width);
    OH_PixelmapImageInfo_GetHeight(real_info, &real_height);
    OH_PixelmapImageInfo_GetRowStride(real_info, &real_rowBytes);
    OH_PixelmapImageInfo_GetPixelFormat(real_info, &pixel_format);
    OH_PixelmapImageInfo_GetAlphaType(real_info, &alpha_type);
    
    OH_PixelmapImageInfo_Release(real_info);
    
    OHDrawingAPI::OH_PixelmapNative_AccessPixels(fPixelmap, &fPixels);
    if (!fPixels) {
        fPixels = new char[real_rowBytes * real_height];
        fHasAccessPixelmap = false;
        fHasFakePixels = true;
    } else {
        fHasAccessPixelmap = true;
    }
    
    fWidth = real_width;
    fHeight = real_height;
    fRowBytes = real_rowBytes;
    fbytesPerPixel = fRowBytes / fWidth;
    
    DrawingHash hasher(DrawingHash::RunningUniqueId());
    hasher.push(fPixels);
    hasher.push(fWidth);
    hasher.push(fHeight);
    hasher.push(fRowBytes);
    fHash = hasher.digest();
}

SkPixelRef::~SkPixelRef() {
    this->callGenIDChangeListeners();
    if (fDrawingPixelmap) {
        OH_Drawing_PixelMapDissolve(fDrawingPixelmap);
    }
    if (fDrawingImage) {
        OH_Drawing_ImageDestroy(fDrawingImage);
    }
    if (fDrawingBitmap) {
        OH_Drawing_BitmapDestroy(fDrawingBitmap);
    }
    if (fHasAccessPixelmap) {
        OHDrawingAPI::OH_PixelmapNative_UnaccessPixels(fPixelmap);
    } else {
        if (fHasFakePixels) {
            delete[] (char *)fPixels;
        }
    }
    if (fPixelmap) {
        OH_PixelmapNative_Release(fPixelmap);
    }
    
}

// This is undefined if there are clients in-flight trying to use us
void SkPixelRef::android_only_reset(int width, int height, size_t rowBytes) {
    fWidth = width;
    fHeight = height;
    fRowBytes = rowBytes;
    // note: we do not change fPixels

    // conservative, since its possible the "new" settings are the same as the old.
    this->notifyPixelsChanged();
}

void SkPixelRef::needsNewGenID() {
    fTaggedGenID.store(0);
    SkASSERT(!this->genIDIsUnique()); // This method isn't threadsafe, so the assert should be fine.
}

uint32_t SkPixelRef::getGenerationID() const {
    uint32_t id = fTaggedGenID.load();
    if (0 == id) {
        uint32_t next = SkNextID::ImageID() | 1u;
        if (fTaggedGenID.compare_exchange_strong(id, next)) {
            id = next;  // There was no race or we won the race.  fTaggedGenID is next now.
        } else {
            // We lost a race to set fTaggedGenID. compare_exchange() filled id with the winner.
        }
        // We can't quite SkASSERT(this->genIDIsUnique()). It could be non-unique
        // if we got here via the else path (pretty unlikely, but possible).
    }
    return id & ~1u;  // Mask off bottom unique bit.
}

void SkPixelRef::addGenIDChangeListener(sk_sp<SkIDChangeListener> listener) {
    if (!listener || !this->genIDIsUnique()) {
        // No point in tracking this if we're not going to call it.
        return;
    }
    SkASSERT(!listener->shouldDeregister());
    fGenIDChangeListeners.add(std::move(listener));
}

// we need to be called *before* the genID gets changed or zerod
void SkPixelRef::callGenIDChangeListeners() {
    // We don't invalidate ourselves if we think another SkPixelRef is sharing our genID.
    if (this->genIDIsUnique()) {
        fGenIDChangeListeners.changed();
        if (fAddedToCache.exchange(false)) {
//             SkNotifyBitmapGenIDIsStale(this->getGenerationID());
        }
    } else {
        // Listeners get at most one shot, so even though these weren't triggered or not, blow them
        // away.
        fGenIDChangeListeners.reset();
    }
}

bool SkPixelRef::buildPixelmapOHOS(const SkImageInfo& info) {
    TRACE_EVENT0("skia-oh", __FUNCTION__ );
    if (fDrawingPixelmap) {
        return true;
    }
    if (!fPixels) {
        SkDebugf("buildPixelmapOHOS no pixels!");
        return false;
    }
    if (info.colorTypeOH() == PIXEL_FORMAT_UNKNOWN) {
        SkDebugf("buildPixelmapOHOS color type not init!");
        return false;
    }
    OH_Pixelmap_InitializationOptions *options = nullptr;
    OH_PixelmapInitializationOptions_Create(&options);
    if (!options) {
        return false;
    }
    OH_PixelmapInitializationOptions_SetWidth(options, fWidth);
    OH_PixelmapInitializationOptions_SetHeight(options, fHeight);
    OH_PixelmapInitializationOptions_SetRowStride(options, fRowBytes);
    OH_PixelmapInitializationOptions_SetSrcPixelFormat(options, info.colorTypeOH());
    OH_PixelmapInitializationOptions_SetPixelFormat(options, info.colorTypeOH());
    OH_PixelmapInitializationOptions_SetAlphaType(options, info.alphaTypeOH());
    
    OH_PixelmapNative_CreateEmptyPixelmap(options, &fPixelmap);
    OH_PixelmapInitializationOptions_Release(options);
    
    fbytesPerPixel = info.bytesPerPixel();
    updatePixelmapPixels();
    
    DrawingHash hasher(fHash);
    hasher.push(DrawingHash::RunningUniqueId());
    fHash = hasher.digest();
    
    if (fPixelmap) {
        fDrawingPixelmap = OH_Drawing_PixelMapGetFromOhPixelMapNative(fPixelmap);
        return true;
    } else {
        SkDebugf("buildPixelmapOHOS create pixelmap failed!");
        return false;
    }
}

bool SkPixelRef::updatePixelmapPixels() {
    if (!fPixels) {
        return false;
    }
    if (!fPixelmap) {
        return false;
    }
    if (fHasAccessPixelmap) {
        return true;
    }
    
    char *tempDst = nullptr;
    OHDrawingAPI::OH_PixelmapNative_AccessPixels(fPixelmap, (void **)&tempDst);
    
    if (tempDst) {
        OH_Pixelmap_ImageInfo *pixelmapInfo;
        OH_PixelmapImageInfo_Create(&pixelmapInfo);
        OH_PixelmapNative_GetImageInfo(fPixelmap, pixelmapInfo);
        
        uint32_t stride;
        OH_PixelmapImageInfo_GetRowStride(pixelmapInfo, &stride);
        for (int i = 0; i < fHeight; i++) {
            memcpy(tempDst + i * stride, (char *)fPixels + i * fRowBytes, fWidth * fbytesPerPixel);
        }
        OH_PixelmapImageInfo_Release(pixelmapInfo);
    }
    OHDrawingAPI::OH_PixelmapNative_UnaccessPixels(fPixelmap);
    
    return true;
}

bool SkPixelRef::buildDrawingImageOHOS(const SkImageInfo& info) {
    TRACE_EVENT0("skia-oh", __FUNCTION__ );
    if (fDrawingImage) {
        return true;
    }
    if (!buildDrawingBitmapOHOS(info)) {
        return false;
    }
    fDrawingImage = OH_Drawing_ImageCreate();
    if (!fDrawingImage || !OH_Drawing_ImageBuildFromBitmap(fDrawingImage, fDrawingBitmap)) {
        OH_Drawing_ImageDestroy(fDrawingImage);
        fDrawingImage = nullptr;
        SkDebugf("OH_Drawing_ImageBuildFromBitmap failed!");
        return false;
    }
    SkDebugf("warning: buildDrawingImageOHOS is time consuming!");
    return true;
}

bool SkPixelRef::buildDrawingBitmapOHOS(const SkImageInfo& info) {
    TRACE_EVENT0("skia-oh", __FUNCTION__ );
    if (fDrawingBitmap) {
        return true;
    }
    if (fPixels && !fDrawingBitmap) {
        OH_Drawing_Image_Info oh_info = {fWidth, fHeight, info.colorTypeOHDrawing(),
                                     info.alphaTypeOHDrawing()};
        fDrawingBitmap = OH_Drawing_BitmapCreateFromPixels(&oh_info, fPixels, fRowBytes);
    }
    if (fDrawingBitmap) {
        return true;
    } else {
        return false;
    }
}


void SkPixelRef::notifyPixelsChanged() {
#ifdef SK_DEBUG
    if (this->isImmutable()) {
        SkDebugf("========== notifyPixelsChanged called on immutable pixelref");
    }
#endif
    TRACE_EVENT0("skia-oh", __FUNCTION__ );
    this->callGenIDChangeListeners();
    this->needsNewGenID();
    if (fPixelmap && fPixels && fMutability != kImmutable && !fHasAccessPixelmap) {
        updatePixelmapPixels();
    }
    
    DrawingHash hasher(fHash);
    hasher.push(DrawingHash::RunningUniqueId());
    fHash = hasher.digest();
}

void SkPixelRef::setImmutable() {
    fMutability = kImmutable;
}

void SkPixelRef::setImmutableWithID(uint32_t genID) {
    /*
     *  We are forcing the genID to match an external value. The caller must ensure that this
     *  value does not conflict with other content.
     *
     *  One use is to force this pixelref's id to match an SkImage's id
     */
    fMutability = kImmutable;
    fTaggedGenID.store(genID);
}

void SkPixelRef::setTemporarilyImmutable() {
    SkASSERT(fMutability != kImmutable);
    fMutability = kTemporarilyImmutable;
}

void SkPixelRef::restoreMutability() {
    SkASSERT(fMutability != kImmutable);
    fMutability = kMutable;
}

sk_sp<SkPixelRef> SkMakePixelRefWithProc(int width, int height, size_t rowBytes, void* addr,
                                         void (*releaseProc)(void* addr, void* ctx), void* ctx) {
    SkASSERT(width >= 0 && height >= 0);
    if (nullptr == releaseProc) {
        return sk_make_sp<SkPixelRef>(width, height, addr, rowBytes);
    }
    struct PixelRef final : public SkPixelRef {
        void (*fReleaseProc)(void*, void*);
        void* fReleaseProcContext;
        PixelRef(int w, int h, void* s, size_t r, void (*proc)(void*, void*), void* ctx)
            : SkPixelRef(w, h, s, r), fReleaseProc(proc), fReleaseProcContext(ctx) {}
        ~PixelRef() override { fReleaseProc(this->pixels(), fReleaseProcContext); }
    };
    return sk_sp<SkPixelRef>(new PixelRef(width, height, addr, rowBytes, releaseProc, ctx));
}
